/*
*Copyright(c) 2020思特诺(Stduino)All right reserved.
*
*This library is open source and free for individual users. 
*
*For commercial use, please contact server@stduino.com.
*/
#include "Lcd12864.h"

void Lcd12864::WriteByte(int data) //spi   iic 
{
 digitalWrite(latchPin, HIGH);
 delayMicroseconds(delaytime);
 shiftOut(dataPin, clockPin, 1, data);
 digitalWrite(latchPin, LOW);
}

void Lcd12864::WriteCommand(int CMD)
{
 int H_data,L_data;
 H_data = CMD;
 H_data &= 0xf0;
 L_data = CMD;
 L_data &= 0x0f;
 L_data <<= 4;
 WriteByte(0xf8);
 WriteByte(H_data);
 WriteByte(L_data);
}

void Lcd12864::WriteData(int CMD)
{
 int H_data,L_data;
 H_data = CMD;
 H_data &= 0xf0;
 L_data = CMD;
 L_data &= 0x0f;
 L_data <<= 4;
 WriteByte(0xfa);
 WriteByte(H_data);
 WriteByte(L_data);
}

void Lcd12864::Begin(int CLOCK,int DATA,int LATCH,int DELAYTIME)
{
 clockPin=CLOCK;
 dataPin=DATA;
 latchPin=LATCH;
 delaytime=DELAYTIME;
 setmode(clockPin,OP_PP_50);
 setmode(dataPin,OP_PP_50);
 setmode(latchPin,OP_PP_50);
 digitalWrite(latchPin, LOW);
 delayMicroseconds(delaytime);
 WriteCommand(0x30);
 WriteCommand(0x0c);
 WriteCommand(0x01);
 WriteCommand(0x06);
}
void Lcd12864::Clean(void)
{
 WriteCommand(0x30);
 WriteCommand(0x01);
}

void Lcd12864::Clean(int X,int Y,int Num)
{
 uint8_t i = 0;
 
 for(i=0;i<Num;i++)
 {
  ShowString(X,Y+i,"  ");
 }
}

void Lcd12864::DisplayString(int X,int Y,String ptr,int dat)
{
 int i;
 
 switch(X)
 {
  case 0:
   Y|=0x80;
   break;
  
  case 1:
   Y|=0x90;
   break;
  
  case 2:
   Y|=0x88;
   break;
  
  case 3:
   Y|=0x98;
   break;
  
  default:
   break;
 }
 
 WriteCommand(Y);
 
 for(i=0;i<dat;i++)
 { 
  WriteData(ptr[i]);
 }
}

void Lcd12864::DisplaySig(int M,int N,int sig)
{
 switch(M)
 {
  case 0:
   N|=0x80;
   break;
   
  case 1:
   N|=0x90;
   break;
   
  case 2:
   N|=0x88;
   break;
   
  case 3:
   N|=0x98;
   break;
   
  default:
   break;
 }
 
 WriteCommand(N);
 WriteData(sig);
}

void Lcd12864::DrawFullScreen(unsigned char *p)
{
 int ygroup,x,y,i;
 int temp;
 int tmp;
 
 for(ygroup=0;ygroup<64;ygroup++)
 {
  if(ygroup<32)
  {
   x=0x80;
   y=ygroup+0x80;
  }else
  {
   x=0x88;
   y=ygroup-32+0x80;
  }
  
  WriteCommand(0x34);
  WriteCommand(y);
  WriteCommand(x);
  WriteCommand(0x30);
  tmp=ygroup*16;
  
  for(i=0;i<16;i++)
  {
   temp=p[tmp++];
   WriteData(temp);
  }
 }
 
 WriteCommand(0x34);
 WriteCommand(0x36);
}

void Lcd12864::ShowString(uint8_t line,uint8_t column,String data)
{
 delay(1);
 DisplayString((line-1),(column-1),data,data.length());
}

void Lcd12864::ShowDouble(int line , int column,double Double)
{
 String s=String(Double,2);
 ShowString(line,column,s);
}

void Lcd12864::ShowInt(int line,int column,int Int)
{
 ShowString(line,column,String(Int));
}
